package ru.spbau.database.group3.filesAndAccess;

import ru.spbau.database.group3.engine.Column;
import ru.spbau.database.group3.engine.Condition;
import ru.spbau.database.group3.filesAndAccess.Page;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * @author: stas
 * @date: 2/2/13
 * @time: 9:35 PM
 */
public class Record implements Serializable {

    public Record(int pid, int sid) {
        this.pid = pid;
        this.sid = sid;
    }

    public int getSid() {
        return sid;
    }


    public int getPid() {
        return pid;
    }

    public Object getColumnValue(Column column) throws IOException {
        Page p = new Page(pid);
        return p.getRecordColumnValue(sid, column);
    }

    public List<Object> getColumnsValue(List<Column> columns) throws IOException {
        ArrayList<Object> values  = new ArrayList<Object>();
        for(Column c : columns) {
            values.add(getColumnValue(c));
        }
        return values;
    }


    public byte[] toByteArray() throws IOException {
        Page p = new Page(pid);
        return p.toByteArray(sid);
    }

    public boolean satisfy(List<Condition> conditions) throws IOException {
        for(Condition c : conditions) {
            if(!c.check(this)) {
                return false;
            }
        }
        return true;
    }

    private int pid;
    private int sid;
    
    @Override
    public String toString() {
    	return "(" + pid + "," + sid + ")";
    }
    
    @Override
    public int hashCode() {
    	return sid * pid;
    }
    
    public boolean equals(Object o) {
    	if (o instanceof Record) {
    		Record oRec = (Record) o;
    		return oRec.pid == pid && oRec.sid == sid;
    	} else {
    		return false;
    	}
    }
}
